<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/5/15 15:37
 * Email: <594652523@qq.com>
 */

namespace App\Console\Commands;

use App\Http\Repositories\Redis\CacheDataRedis;
use App\Models\CourseDuty;
use App\Models\Users;
use App\Models\UserScoreRecord;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SignScore extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sign:score';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户签到增加积分';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $giveScore = CacheDataRedis::getRedisInstance()->systemConfig('basic.sign_score') ?? 0;
        if (empty($giveScore)) {//设置签到送积分为0时不处理
            Log::info('平台未设置签到送积分,不做处理');
            return;
        }
        //赠送积分给上课签到和下课签到同时打卡有记录的
        $query = CourseDuty::where('need_give', 1)->whereIn('sign_type', [1, 2])->groupBy('course_section_id', 'user_id')
            ->selectRaw('user_id,course_section_id,COUNT(DISTINCT sign_type) AS sign_types')
            ->having('sign_types', 2)->orderBy('course_section_id');
        $query->chunk(100, function ($list) use ($giveScore) {
            foreach ($list as $item) {
                try {
                    DB::beginTransaction();
                    //更新赠送状态
                    CourseDuty::where('user_id', $item['user_id'])->where('course_section_id', $item['course_section_id'])->update(['need_give' => 2]);
                    //增加积分记录，业务id暂用course_section_id
                    UserScoreRecord::create(['user_id' => $item['user_id'], 'qty' => $giveScore, 'buss_type' => 2, 'buss_id' => $item['course_section_id'], 'remark' => '签到赠送积分']);
                    //增加用户积分
                    Users::where('id', $item['user_id'])->increment('score', $giveScore);
                    DB::commit();
                    Log::info('用户' . $item['user_id'] . ',章节' . $item['course_section_id'] . '处理成功');
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::error('签到处理失败:' . $e->getMessage() . '，user_id:' . $item['user_id'] . ',course_section_id:' . $item['course_section_id']);
                }

            }
        });
    }

}
